package com.etonedu.meals.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.bean.AttendanceDate;
import com.etonedu.meals.bean.Face1Bean;
import com.etonedu.meals.bean.FaceResult;
import com.etonedu.meals.bean.Result;
import com.etonedu.meals.common.SPConst;
import com.etonedu.meals.dao.DaoUtils;
import com.etonedu.meals.enumeration.APICodeEnum;
import com.etonedu.meals.http.HttpUrl;
import com.etonedu.meals.http.LogReportUtils;
import com.etonedu.meals.http.ParamsUtils;
import com.etonedu.meals.utils.MD5Utils;
import com.etonedu.meals.utils.SharedPreferencesUtil;
import com.etonedu.meals.utils.Utils;
import com.etonedu.meals.utils.XXTEAV2;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import io.objectbox.Box;
import io.objectbox.BoxStore;

public class UploadService extends Service {

    private UploadThead uploadThead;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        upload();
        LogUtils.e("onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void upload() {
        uploadThead = new UploadThead();
        uploadThead.start();
    }

    private class UploadThead extends Thread {
        @Override
        public void run() {
            super.run();
            while (true) {
                AttendanceDate date = null;
                Box<AttendanceDate> box = DaoUtils.getBoxAttendanceDate();
                try {

                    date = box.query().build().findFirst();
                } catch (Exception e) {
                    e.printStackTrace();
                    UploadService.this.sleep(3);
                }
                if (date != null) {

                    String mode = date.getMode();
                    if (!"5".equals(mode)) {
                        String face = date.getFace();
                        if (!Utils.isEmpty(face)) {
                            uploadFace(date);
                        } else {
                            int noClass = date.getNoClass();
                            LogUtils.e("noClass = "+noClass);
                            if (noClass == 1) {
                                box.remove(date);
                            } else {
                                upload(date);
                            }
                        }
                    } else {
                        String face = date.getFace();
                        if (!Utils.isEmpty(face)) {
                            uploadFace(date);
                        } else {
                            uploadAtten(date);
                        }
                    }
                } else {
                    UploadService.this.sleep(3);
                }
            }

        }
    }

    private void sleep(int i) {
        try {
            Thread.sleep(i * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void upload(AttendanceDate date) {
        getUploadUrl(date);
    }

    private void getUploadUrl(AttendanceDate date) {
        try {
            SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(x.app());
            String apiCode = APICodeEnum.agw30161018.getApiCode();
            String type = spu.getString(SPConst.ENVIRONMENT);
            String token = spu.getString(SPConst.TOKEN);
//        String environType = EnvironmentType.TEST01.getType();

            String url = spu.getString(SPConst.AGW_30161018);
            if (!Utils.isEmpty(url)) {
                upload(url, token, date);
                return;
            }

            String params = ParamsUtils.getURLParams(type, apiCode);
            RequestParams requestParams = new RequestParams(HttpUrl.URL);
            requestParams.setReadTimeout(60 * 1000);
            requestParams.setConnectTimeout(60 * 1000);
            requestParams.setBodyContent(params);
            String result = x.http().postSync(requestParams, String.class);

            Type typeToken = new TypeToken<Result>() {
            }.getType();
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            Result r = gson.fromJson(result, typeToken);

            String data = r.getData();

            String deData = "";

            if (HttpUrl.DOMAIN.equals("http://agw.52ess.cn/api")) {
                deData = XXTEAV2.decryptBase64StringToString(data, MD5Utils.ENCRY_DECRYPT_KEY);
            } else if (HttpUrl.DOMAIN.equals("http://agw.woniukid.cn/api")) {
                deData = XXTEAV2.decryptBase64StringToString(data, MD5Utils.PROD_ENCRY_DECRYPT_KEY);
            }

            LogUtils.d("deData = " + deData);
            JSONObject jsonObject = new JSONObject(deData);
            String fullUrl = jsonObject.optString("fullUrl");
            LogUtils.e("fullUrl = " + fullUrl);
            spu.setString(SPConst.AGW_30161018, fullUrl);
            upload(fullUrl, token, date);

        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("获取上传公共地址超时", pagek, Utils.getLineInfo(), time1);
        }

    }

    private void upload(String url, String token, AttendanceDate date) {

        String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        String pagek = "com.etonedu.general.edu.service";
        int cardFlag = date.getAttenType();
        LogReportUtils.log("上传考勤信息:carldFlag = " + cardFlag, pagek, Utils.getLineInfo(), time1);

        LogUtils.e("上传考信息");
        try {
            String apiCode = APICodeEnum.agw30161018.getApiCode();
            String header = ParamsUtils.getHeader(apiCode, token);

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("deviceCode", Utils.getDevCode());
            if (cardFlag == 1) {
                hashMap.put("cardNo", date.getCardNo());
            } else if (cardFlag == 2) {
                hashMap.put("userId", date.getUserId());
                hashMap.put("roleType", date.getRoleType());

            }
            hashMap.put("attenTime", date.getAttenTime());
            String base64 = date.getImageStr();
            if (!Utils.isEmpty(base64)) {
                hashMap.put("imageStr", base64);
            }

            String face = date.getFace();
            if (!Utils.isEmpty(face)) {
                hashMap.put("inUserId",date.getUserIds());
            }
            hashMap.put("isUpdatePic", date.getIsUpdatePic());

            Gson gson = new Gson();
            String json = gson.toJson(hashMap);
            LogReportUtils.log("上传考勤信息:参数 = " + json, pagek, Utils.getLineInfo(), time1);
//            LogUtils.e("json = "+json);
            LogReportUtils.log("卡号:"+date.getCardNo()+",请求参数:"+json+",apiCode = "+apiCode,pagek, Utils.getLineInfo(), time1);
            String data = ParamsUtils.getEncrypt(apiCode, json);

            String data1 = ParamsUtils.getParams(apiCode, data);

            RequestParams params = new RequestParams(url);
            params.setReadTimeout(60 * 1000);
            params.setConnectTimeout(60 * 1000);
            params.addHeader("authStr", header);
            params.setBodyContent(data1);
            String result = x.http().postSync(params, String.class);

            LogReportUtils.log("卡号:" + date.getCardNo()+","+result+",apiCode = "+apiCode, pagek, Utils.getLineInfo(), time1);

            LogUtils.e("cardNum = " + date.getCardNo() + ",apiCode = " + apiCode + ",result = " + result);

            Type typeToken = new TypeToken<Result>() {
            }.getType();

            Result r = gson.fromJson(result, typeToken);

            String data2 = r.getData();

            String deData = "";
            if (!Utils.isEmpty(data2)) {
                deData = ParamsUtils.getDecrypt(apiCode, data2);
            }
            LogUtils.e("cardNum = " + date.getCardNo() + ",apiCode = " + apiCode + ",deData = " + deData);

            LogReportUtils.log("卡号:" + date.getCardNo()+","+deData+",apiCode = "+apiCode, pagek, Utils.getLineInfo(), time1);

            if (cardFlag == 1) {
//                LogReportUtils.logCardNum("", date.getConut(), date.getCardNo(), time1, "0", "");
            }
//            dao.delete(date);
            Box<AttendanceDate> box = DaoUtils.getBoxAttendanceDate();
            box.remove(date);
            String path = date.getPath();
            if (!Utils.isEmpty(path)) {
                FileUtils.delete(path);
            }


        } catch (Exception e) {
            LogUtils.e(Utils.getLineInfo());
            e.printStackTrace();
        } catch (Throwable throwable) {
            LogUtils.e(Utils.getLineInfo());
            throwable.printStackTrace();
            throwable.printStackTrace();
            String time2 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek1 = "com.etonedu.general.edu.service";
            LogReportUtils.log("上传考勤信息超时", pagek1, Utils.getLineInfo(), time2);
        }

    }

    private void uploadAtten (AttendanceDate date) {
        getUploadAttenUrl(date);
    }

    private void getUploadAttenUrl(AttendanceDate date) {
        try {
            SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(x.app());
            String apiCode = APICodeEnum.agw30161023.getApiCode();
            String type = spu.getString(SPConst.ENVIRONMENT);
            String token = spu.getString(SPConst.TOKEN);
//        String environType = EnvironmentType.TEST01.getType();

            String url = spu.getString(SPConst.AGW_30161023);
            if (!Utils.isEmpty(url)) {
                uploadAtten(url, token, date);
                return;
            }

            String params = ParamsUtils.getURLParams(type, apiCode);
            RequestParams requestParams = new RequestParams(HttpUrl.URL);
            requestParams.setBodyContent(params);
            String result = x.http().postSync(requestParams, String.class);

            Type typeToken = new TypeToken<Result>() {
            }.getType();
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            Result r = gson.fromJson(result, typeToken);

            String data = r.getData();

            String deData = "";

            if (HttpUrl.DOMAIN.equals("http://agw.52ess.cn/api")) {
                deData = XXTEAV2.decryptBase64StringToString(data, MD5Utils.ENCRY_DECRYPT_KEY);
            } else if (HttpUrl.DOMAIN.equals("http://agw.woniukid.cn/api")) {
                deData = XXTEAV2.decryptBase64StringToString(data, MD5Utils.PROD_ENCRY_DECRYPT_KEY);
            }

            LogUtils.d("deData = " + deData);
            JSONObject jsonObject = new JSONObject(deData);
            String fullUrl = jsonObject.optString("fullUrl");
            LogUtils.e("fullUrl = " + fullUrl);
            spu.setString(SPConst.AGW_30161023, fullUrl);
            uploadAtten(fullUrl, token, date);

        } catch (Exception e) {
            e.printStackTrace();
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("获取上传公共地址超时", pagek, Utils.getLineInfo(), time1);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("获取上传公共地址超时", pagek, Utils.getLineInfo(), time1);
        }
    }

    private void uploadAtten(String url,String token,AttendanceDate date) {
        try {
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("上传课室考勤信息", pagek, Utils.getLineInfo(), time1);

            String apiCode = APICodeEnum.agw30161023.getApiCode();
            String header = ParamsUtils.getHeader(apiCode, token);

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("deviceCode", Utils.getDevCode());
            hashMap.put("reqResult", 1);
            int cardFlag = date.getAttenType();
            if (cardFlag == 1) {
                String cardNo = date.getCardNo();
                hashMap.put("cardNo", cardNo);
            } else if (cardFlag == 2) {
                String userId = date.getUserId();
                hashMap.put("userId", userId);
            } else if (cardFlag == 3) {
                String userId = date.getUserIds();
                hashMap.put("inUserId", userId);
            }

            long currTime = System.currentTimeMillis();
            hashMap.put("attenTime", Utils.timestamp2String1(currTime, "yyyyMMddHHmmss"));

            Gson gson = new Gson();
            String json = gson.toJson(hashMap);

            String data = ParamsUtils.getEncrypt(apiCode, json);

            String data1 = ParamsUtils.getParams(apiCode, data);

            RequestParams params = new RequestParams(url);
            params.setConnectTimeout(60 * 1000);
            params.setReadTimeout(60 * 1000);
            params.addHeader("authStr", header);
            params.setBodyContent(data1);
            String result = x.http().postSync(params, String.class);

            Type typeToken = new TypeToken<Result>() {
            }.getType();
            Result r = gson.fromJson(result, typeToken);

            String resultData = r.getData();

            String deData = ParamsUtils.getDecrypt(apiCode,resultData);

            LogUtils.e("deData = " + deData);

            if (!Utils.isEmpty(deData)) {
                JSONObject jsonObject = new JSONObject(deData);
                String jsonStr = jsonObject.optString("respDataStr");

                JSONObject object = new JSONObject(jsonStr);
                JSONObject jsonObject1 = object.optJSONObject("data");
                if (jsonObject1 != null) {
                    int kaoqinId = jsonObject1.optInt("kaoqinId");
                    uploadPublicAttenURL(url, token, kaoqinId, date);
                } else {
                    Box<AttendanceDate> box = DaoUtils.getBoxAttendanceDate();
                    box.remove(date);
                    String path = date.getPath();
                    if (!Utils.isEmpty(path)) {
                        FileUtils.delete(path);
                    }
                }
            } else {
                Box<AttendanceDate> box = DaoUtils.getBoxAttendanceDate();
                box.remove(date);
                String path = date.getPath();
                if (!Utils.isEmpty(path)) {
                    FileUtils.delete(path);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("获取上传公共地址超时", pagek, Utils.getLineInfo(), time1);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("获取上传公共地址超时", pagek, Utils.getLineInfo(), time1);
        }
    }

    public void uploadPublicAttenURL(String url,String token,int kaoqinId,AttendanceDate date){
        try {
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("上传课室考勤信息", pagek, Utils.getLineInfo(), time1);

            String apiCode = APICodeEnum.agw30161023.getApiCode();
            String header = ParamsUtils.getHeader(apiCode, token);

            HashMap<String, Object> hashMap = new HashMap<>();

            hashMap.put("imageStr", date.getImageStr());
            hashMap.put("kaoqinId", kaoqinId);
            long currTime = System.currentTimeMillis();
            hashMap.put("attenTime", Utils.timestamp2String1(currTime, "yyyyMMddHHmmss"));
            hashMap.put("reqResult", "1");

            Gson gson = new Gson();
            String json = gson.toJson(hashMap);

            String data = ParamsUtils.getEncrypt(apiCode, json);

            String data1 = ParamsUtils.getParams(apiCode, data);

            RequestParams params = new RequestParams(url);
            params.setConnectTimeout(60 * 1000);
            params.setReadTimeout(60 * 1000);
            params.addHeader("authStr", header);
            params.setBodyContent(data1);
            String result = x.http().postSync(params, String.class);

            Type typeToken = new TypeToken<Result>() {
            }.getType();
            Result r = gson.fromJson(result, typeToken);

            String resultData = r.getData();

            String deData = ParamsUtils.getDecrypt(apiCode,resultData);
            LogUtils.e("deData = " + deData);

            Box<AttendanceDate> box = DaoUtils.getBoxAttendanceDate();
            box.remove(date);

            String path = date.getPath();
            if (!Utils.isEmpty(path)) {
                FileUtils.delete(path);
            }

            LogReportUtils.log("上传课室考勤信息成功"+deData,pagek,Utils.getLineInfo(),time1);
        } catch (Exception e) {
            e.printStackTrace();
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("获取上传公共地址超时", pagek, Utils.getLineInfo(), time1);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            String time1 = Utils.timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
            String pagek = "com.etonedu.general.edu.service";
            LogReportUtils.log("获取上传公共地址超时", pagek, Utils.getLineInfo(), time1);
        }
    }

    private void uploadFace(AttendanceDate date) {

        String userIds1 = date.getUserIds();
        if (!Utils.isEmpty(userIds1)) {
            upload(date);
        } else {

            SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(x.app());
            RequestParams params = new RequestParams(HttpUrl.FACE_URL);
            params.setConnectTimeout(60 * 1000);
            params.setReadTimeout(60 * 1000);

            HashMap<String, Object> hashMap = new HashMap<>();
            int schoolId = spu.getInt(SPConst.SCHOOL_ID);
            hashMap.put("org_id", schoolId);
            hashMap.put("req_id", UUID.randomUUID().toString());
            hashMap.put("base64_image", date.getImageStr().trim());

            Gson gson = new Gson();
            String content = gson.toJson(hashMap);

            LogUtils.json(content);

            params.setBodyContent(content);

            try {
                String relust = x.http().postSync(params, String.class);

                LogUtils.e("relust = "+relust);

                Type type = new TypeToken<FaceResult>() {
                }.getType();
                FaceResult faceResult = gson.fromJson(relust, type);

                if (faceResult.getCode() == 1) {
                    Box<AttendanceDate> box = DaoUtils.getBoxAttendanceDate();
                    box.remove(date);
                    FileUtils.delete(date.getPath());
                    return;
                }

                List<Face1Bean> list = faceResult.getResult();
                if (!Utils.listIsNullOrEmpty(list)) {
                    String userIds = "";
                    Face1Bean face1Bean = list.get(0);
                    userIds = face1Bean.getUser_id();

                    Box<AttendanceDate> box = DaoUtils.getBoxAttendanceDate();

                    if ("other".equals(userIds)) {
                        box.remove(date);
                        FileUtils.delete(date.getPath());
                        return;
                    }

                    date.setUserIds(userIds);
                    box.put(date);
                    String mode = date.getMode();
                    if (!"5".equals(mode)) {
                        upload(date);
                    } else {
                        uploadAtten(date);
                    }
                }

                LogUtils.e("result = " + relust);
            } catch (Exception e) {
                e.printStackTrace();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }
}
